package com.example.demo.service;

import com.example.demo.common.JwtTokenUtils;
import com.example.demo.dao.AdminDao;
import com.example.demo.entity.Admin;
import com.example.demo.entity.Params;
import com.example.demo.exception.CustomException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AdminService {

    @Resource
    private AdminDao adminDao;

    //查询所有
    public List<Admin> findAll() {
        return adminDao.selectAll();
    }

    public PageInfo<Admin> findBySearch(Params params) {
        //开启分页查询
        PageHelper.startPage(params.getPageNum(), params.getPageSize());//PageHelper.startPage工具类进行分页
        List<Admin> bySearch = adminDao.findBySearch(params);
        return PageInfo.of(bySearch);
    }

    public void add(Admin admin) {
        if (admin.getName() == null || "".equals(admin.getName())) {
            throw new CustomException("用户名不能为空");
        }
        Admin loginUser = adminDao.findByName(admin.getName());
        if (loginUser != null) {
            throw new CustomException("该用户名已存在");
        }
        //密码简单判断
        if (admin.getPassword() == null) {
            admin.setPassword("123456");
        }
        adminDao.insertSelective(admin);
    }

    public void update(Admin admin) {
        adminDao.updateByPrimaryKey(admin);
    }

    public void delete(Integer id) {
        adminDao.deleteByPrimaryKey(id);
    }

    public Admin login(Admin admin) {
        //1.进行非空判断
        if (admin.getName() == null || "".equals(admin.getName())) {
            throw new CustomException("用户名不能为空");
        }
        if (admin.getPassword() == null || "".equals(admin.getPassword())) {
            throw new CustomException("密码不能为空");
        }
        //2.数据库根据用户名和密码查询对应的管理员信息
        Admin loginUser = adminDao.findByNameAndPassword(admin.getName(), admin.getPassword());
        if (loginUser == null) {
            throw new CustomException("输入的用户名或密码有误");
        }
        //生成该登录用户的token
        String token = JwtTokenUtils.genToken(loginUser.getId().toString(), loginUser.getPassword());
        loginUser.setToken(token);
        return loginUser;
    }

    public Admin findById(Integer id) {
        return adminDao.selectByPrimaryKey(id);
    }
}
